<?
class Main_model extends CI_Model
{
	public $currentPage = '';
	public $template = false;

	function __construct()
	{
		parent::__construct();
	}
	
	function getMenuPages()
	{	
		$this->db->where('pMenu', 1);
		$this->db->where('dAllowed >', 0);
		$this->db->where('dDeleted', 0);
		$this->db->order_by('pOrder DESC');
		return $this->db->get('page')->result();
	}

	function getMainPageUrl()
	{
		$res = $this->db->where(array(
			'pMain'=>1,
			'dDeleted'=>0,
			'dAllowed'=>0
		))->get('page')->row();
		return $res ? $res->pUrl : '';
	}
	
	function getBlockArticles($id, $category = false, $count = null, $from = 0)
	{
		if ($category) {
			$this->db->join('article_category ac', 'ac.tArticle = self.id');
			$this->db->where('ac.tCategory', $category);
		}
		
		if (is_arr($id)) {
			$this->db->where_in('self.tBlog', $id);
		} elseif($id) {
			$this->db->where('self.tBlog', $id);
		}
		$this->db->where('self.dDeleted', 0);
		$this->db->where('self.dAllowed >', 0);
		if ($count === true) {
			return $this->db->count_all_results('article self');
		} else {
			$this->db->order_by('self.id desc');
			if (is_numeric($count)){
				$this->db->limit((int)$count, $from);
			}
			$res = $this->db->get('article self')->result();
			$cats = $this->getArticleCategoriesWithGroup( extractFieldFromDataArray($res, 'id') );
			foreach ($res as &$val) {
				$val->tCategory = isset($cats[$val->id]) ? $cats[$val->id] : array();
			}
			return $res;
		}
	}
	
	function getContentByUrl()
	{
		$categoryId = 0;
		$category = false;
		$paginationBaseUrl = '';
		$from = 0;
		$uri_segment = 3;
		$content = '';
		$isArticle = false;

		if (!$this->uri->segment(1))
		{
			$this->db->where('pMain', 1);
			$this->db->where('dDeleted', 0);
			$this->db->where('dAllowed >', 0);
			$res = $this->db->get('page');
			if (!$res->num_rows)
			{
				$this->db->where('dDeleted', 0);
				$this->db->where('dAllowed >', 0);
				$this->db->order_by('id');
				$res = $this->db->get('page',1);
			}
		}
		else
		{
			if ($this->uri->segment(2) == 'category' && ($categoryId = (int)($this->uri->segment(3))))
			{
				$this->db->where('id', $categoryId);
				if (!($category = $this->db->get('category')->row()))
					return array(
						'content' => $this->load->view("404", null, true),
						'title' => "Страница не найдена"
					);
				
				$from = (int)$this->uri->segment(5);
				$uri_segment = 5;

				$this->db->where('pUrl', $this->uri->segment(1));
				$this->db->where('dDeleted', 0);
				$this->db->where('dAllowed >', 0);
				$res = $this->db->get('page');

				if ($res->row()->pType != 2)
				{
					$this->db->where('id', $category->tPage);
					$this->db->where('dDeleted', 0);
					$res = $this->db->get('page');
				}
			}
			else
			{
				$this->db->where('pUrl', $this->uri->segment(1));

				$this->db->where('dDeleted', 0);
				if (!$this->user->checkRight(4)) {
					$this->db->where('dAllowed >', 0);
				}
				$res = $this->db->get('page');

				if ($res->num_rows) {
					$page = $res->row();
					if ($page->pType == 1 || $page->pType == 2) {
						if ($this->uri->segment(2)) {
							if ($this->uri->segment(2) == 'page') {
								$from = (int)($this->uri->segment(3));
							} else {
								$this->db->where('pUrl', $this->uri->segment(2));
								$this->db->where('tBlog', $page->id);
								$this->db->where('dDeleted', 0);
								$res = $this->db->get('article');
								$isArticle = true;
							}
						}
						
						$paginationBaseUrl = '/'.$page->pUrl;
					}
				}
			}
		}

		if ($res->num_rows)
		{
			$res = $res->row();

			if ($this->settings->data->considerVisits == '1')
			{
				$this->load->library('User_agent');
				if (!$this->agent->is_robot())
				{
					$visitData = array(
						'pType' => $isArticle?1:0,
						'tId' => $res->id,
						'dCreated' => now(),
						'tUser' => $this->user->id,
						'pIP' => $_SERVER['REMOTE_ADDR'],
						'pReferer' => isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:'',
					);
					$this->db->insert('visit', $visitData);
				}
			}

			$data = array(
				'page' => $res
			);

			$data['page']->orId = $data['page']->id;

			$this->currentPage = $data['page'];
			if (
				(isset($data['page']->dAllowed) && ($data['page']->dAllowed == 0)) &&
				!($this->user->checkRight(1) ||$this->user->checkRight(2) ||$this->user->checkRight(4) ||$this->user->checkRight(8) )
			)
			{
				header("Status: 404 Not Found");
				$content = $this->load->view("censored", null, true);
				$title = 'Страница удалена';
			}
			elseif (isset($data['page']->pType))
			{
				if ($data['page']->pType == 1 || $data['page']->pType == 2)
				{
					if ($data['page']->pType == 2)
					{
						$data['page']->id = array_merge(json_decode($data['page']->pText), array($data['page']->id));
						$data['blogs'] = $this->getBlogs($data['page']->id);
					}
					else
					{
						$data['blogs'] = array(
							$data['page']->id => $data['page']
						);
					}

					$blogSize = $data['page']->pBlogSize? abs($data['page']->pBlogSize): $this->settings->data->blogSize;

					$data['categories'] = $this->getCategories($data['page']->id);
					$data['entry'] = $this->getBlockArticles(
						$data['page']->id,
						$categoryId,
						$blogSize,
						$from
					);

					$data['users'] = $this->user->getUsernamesByIds(extractFieldFromDataArray($data['entry'], 'tUserCreated'));

					if ($category)
					{
						$paginationBaseUrl = '/'.$data['page']->pUrl.'/category/'.$categoryId;
						$data['activeCategory'] = $category;
					}
					
					if (!$paginationBaseUrl)
						$paginationBaseUrl = '/'.$data['page']->pUrl;

					$this->load->library('pagination');

					$config = array(
						'base_url' => $paginationBaseUrl.'/page/',
						'total_rows' => $this->getBlockArticles($data['page']->id, $categoryId, true),
						'per_page' => $blogSize,
						'uri_segment' => $uri_segment
					);

					$this->pagination->initialize($config);
					$data['pagination'] = $this->pagination->create_links();

					$content = $this->load->view("content_list", $data, true);
				}
				else
				{
					if ($data['page']->pType == 3)
					{
						$this->load->model('feedback_model', 'fb');
						$data['feedback'] = $this->fb->getFeedback($data['page']->id);
						$data['addJS'] = array('/js/_carcass/feedback.js');
					}
					$content = $this->load->view("content", $data, true);
				}
			}
			else
			{
				$data['category'] = $this->getArticleCategoriesNames($data['page']->id);
				$comments = $this->getComments($data['page']->id);
				$data['commentsCount'] = $comments['count'];

				$userIds = array();
				foreach ($comments['comments'] as $cVal) {
					$userIds = array_merge($userIds, extractFieldFromDataArray($cVal, 'tUser'));
				}

				$userIds[]=$data['page']->tUserCreated;
				$data['users'] = $this->user->getUsernamesByIds(array_unique($userIds));

				$sortedComments = array();
				foreach ($comments['comments'] as $comment) {
					$comment->html = $this->load->view('oneComment', array(
						'comment' => $comment,
						'users' => $data['users'],
						'level' => 0
					), true);
					$sortedComments[$comment->tComment][]=$comment;
				}
				$data['comments'] = $sortedComments;

				$content = $this->load->view("content", $data, true);
			}

			$resArray = array(
				'content' => $content,
				'title' => isset($title)? $title: $data['page']->pName.(($isArticle && $this->settings->data->authorInTitle == '1')?' - '.$data['users'][$data['page']->tUserCreated]:''),
				'id' => $data['page']->id,
				'addStyles' => $this->getAddStyles($data['page']->orId, $isArticle? $data['page']->tBlog: 0)
			);

			if ($isArticle)
			{
				$resArray['description'] = $res->pShortText;
				$resArray['og_image'] = base_url().'uploads/articles/'.$res->id.'/thumb200/'.$res->pImg;
			}
			return $resArray;
		}
		else
		{
			header("Status: 404 Not Found");
			return array(
				'content' => $this->load->view("404", null, true),
				'title' => "Страница не найдена"
			);
		}
	}
	
	function getCategory($id)
	{
		$this->db->select('category.*, page.pName as "pageName"');
		$this->db->where('category.id', $id);
		$this->db->where('page.pType', 1);
		$this->db->where('page.dDeleted', 0);
		$this->db->where('page.dAllowed >', 0);
		$this->db->join('page', 'page.id = category.tPage');
		$category = $this->db->get('category')->row();
		return ($category) ? $category : false;
	}

	function getCategories($tPage = 0)
	{
		if (is_arr($tPage)) {
			$this->db->where_in('cat.tPage', $tPage);
		} elseif($tPage) {
			$this->db->where('cat.tPage', $tPage);
		}

		// Пустые нам не нужны
		$this->db->join('article_category ac', 'ac.tCategory = cat.id');

		$res = $this->db->get('category cat')->result();
		$exp = array();
		foreach ($res as $val) {
			$exp[$val->id] = $val->pName;
		}
		return $exp;
	}

	function getCategoriesById($ids)
	{
		if (is_arr($ids)) {
			$this->db->where_in('cat.id', $ids);
		} elseif($ids) {
			$this->db->where('cat.id', $ids);
		}

		$res = $this->db->get('category cat')->result();
		$exp = array();
		foreach ($res as $val) {
			$exp[$val->id] = $val->pName;
		}
		return $exp;
	}
	
	function getBlock($id)
	{
		$this->db->where('id', $id);
		return $this->db->get('blocks')->row()->pText;
	}
	
	function getLastestPages($limit = 10, $blog = false, $exception = false)
	{
		$this->db->limit($limit);
		$this->db->select('article.*, page.pUrl as blogUrl');
		if ($blog)
			$this->db->where('tBlog', abs($blog));
		if (is_arr($exception))
			$this->db->where_not_in('tBlog', $exception);
		$this->db->where('article.dDeleted', 0);
		$this->db->where('article.dAllowed >', 0);
		$this->db->order_by('article.dCreated DESC');
		
		$this->db->join('page', 'page.id = article.tBlog');

		return $this->db->get('article')->result();
	}

	function getRightBlock()
	{
		$data = array(
			'text' => $this->db->where('id', 1)->get('blocks')->row()->pText
		);

		preg_match_all('/\{.+\}/', $data['text'], $matches);

		foreach ($matches[0] as $val)
		{
			$newBlock = '';
			$entry = explode('|', substr($val, 1, -1));
			switch ($entry[0])
			{
				case 'last_news':
					if (!($count = abs($entry[1])))
						$count = 10;
					if (isset($entry[3]))
						$exc = array_map('abs', explode(',', $entry[3]));
					else
						$exc = false;

					$newBlock = $this->load->view('last_news', array(
							'lastestPages' => $this->getLastestPages($count, false, $exc),
							'caption' => isset($entry[2])?$entry[2]:''
						), true);
					break;

				default:
					if (strpos($entry[0], 'page_') == 0 && (sizeof($page = explode('_', $entry[0]))==2))
					{
						if (!($count = abs($entry[1])))
							$count = 10;
						$newBlock = $this->load->view('last_news', array(
							'lastestPages' => $this->getLastestPages($count, $page[1]),
							'caption' => isset($entry[2])?$entry[2]:''
						), true);
					}
			}

			$pos = strpos($data['text'], $val);
			$data['text'] = substr($data['text'], 0, $pos).$newBlock.substr($data['text'], $pos + strlen($val));
		}

		
		return $this->load->view('rightContent', $data, true);
	}

	function getBlogs($ids = array())
	{
		if (empty($ids))
			return false;
		$this->db->where_in('id', $ids);
		$this->db->where('dAllowed >', 0);
		$this->db->where('dDeleted', 0);
		$this->db->where('pType', 1);
		return setKeys($this->db->get('page')->result(), 'id');
	}

	function addComment($page, $text = '', $comment = 0)
	{
		if (!$this->user->id)
			return false;

		$upd = array(
			'tUser' => $this->user->id,
			'tArticle' => $page,
			'pText' => nl2br(htmlEscape(trim(preg_replace('/(\s)+/', '$1', $text)))),
			'dCreated' => now(),
			'tComment' => $comment
		);

		$this->db->insert('comment', $upd);
		$upd['id'] = $this->db->insert_id();
		return $upd;
	}

	function getComments($article)
	{
		$comments = $this->db->where('tArticle', $article)->where('dDeleted', 0)->order_by('dCreated')->get('comment')->result();
		return array(
			'comments' => $comments,
			'count' => count($comments)
		);
	}

	function getCommentsCount($article = 0, $deleted = false)
	{
		if ($article)
			$this->db->where('tArticle', $article);
		
		$this->db->where($deleted? 'dDeleted >': 'dDeleted', 0);

		return $this->db->count_all_results('comment');
	}

	function deleteComment($id = 0)
	{
		$ids = array();
		$newIds = array($id);

		// поиск всех дочерних комментариев текущего коммента
		do {
			$ids = array_merge($ids, $newIds);
			$comments = $this->db->where_in('tComment', $newIds)->get('comment')->result();
			$newIds = extractFieldFromDataArray($comments, 'id');
		}
		while (!empty($newIds));

		return $this->db->where_in('id', $ids)->update('comment', array(
			'dDeleted' => now(),
			'tUserDeleted' => $this->user->id,
		));
	}

	function getArticle($ids, $isset = false)
	{
		$this->db->where('dDeleted', 0);

		if (is_array($ids))
			$this->db->where_in('id', $ids);
		else
			$this->db->where('id', $ids);

		if ($isset)
			return $this->db->count_all_results('article');
		else
			return $this->db->get('article')->result();
	}

	function getArticles($ids = array())
	{
		if (empty($ids))
			return array();

		$this->db
			->select('a.id, a.pName, a.pUrl, a.tBlog, p.pUrl as "blogUrl"')
			->where('a.dDeleted', 0)
			->where_in('a.id', $ids)
			->join('page p', 'p.id = a.tBlog');
		$res = $this->db->get('article a')->result();
		
		$exp = array();
		foreach ($res as $val)
			$exp[$val->id] = $val;
		return $exp;
	}

	function getSubMenu($ids)
	{
		$ids = (array)$ids;
		if (empty($ids))
			return array();

		$res = $this->db->select('id, pName, pUrl')->where(array(
			'dDeleted' => 0,
			'dAllowed >' => 0,
		))->where_in('tPage', $ids)->get('page')->result();

		if (!$res)
		{
			$pages = $this->db
				->select('parents.id')
				->join('page parents', 'parents.id = p.tPage')
				->where_in('p.id', $ids)
				->where(array(
					'p.dDeleted' => 0,
					'p.dAllowed >' => 0,
					'parents.dDeleted' => 0,
					'parents.dAllowed >' => 0,
				))->get('page p')->result();

			if (!$pages)
				return array();

			$pages = extractFieldFromDataArray($pages, 'id');


			$res = $this->db->select('id, pName, pUrl')->where(array(
				'dDeleted' => 0,
				'dAllowed >' => 0,
			))->where_in('tPage', $pages)->get('page')->result();
		}

		return $res;
	}

	function canDeleteComment($id=0)
	{
		$res = $this->db->where('id', $id)->get('comment')->row();
		if (empty($res))
			return 'Этот комментарий не существует';
		if ($res->dDeleted)
			return 'Этот комментарий уже удалён';
		if ($res->tUser != $this->user->id)
			return 'Вам нельзя удалять этот комментарий!!!111';
		if ($res->dCreated < now()-300)
			return 'Прошло 5 минут с момента создания комментария - этот комментарий насегда останется здесь.';
		return true;
	}

	function getTemplate()
	{
		$template = empty($this->config->config['template'])?'main':$this->config->config['template'];

		if (!$this->template)
		{
			if (is_dir('templ/'.$template.'/views'))
				$this->template = $template;
			else
				$this->template = 'main';
		}
		
		return $this->template;
	}

	function getAddStyles($id = 0, $isArticle = 0)
	{
		$this->db->where( array(
			'tPage' => $id,
			'pArticle' => $isArticle?1:0
		));

		if ($isArticle) {
			$this->db->or_where(array(
				'tPage' => $isArticle,
				'pArticle' => 0
			));
		}

		return $this->db->get('additional_style')->result();
	}

	function getArticleCategories($ids)
	{
		if (is_array($ids)){
			$this->db->where_in('tArticle', $ids);
		} else {
			$this->db->where('tArticle', $ids);
		}

		return extractFieldFromDataArray($this->db->get('article_category')->result(), 'tCategory');
	}

	function getArticleCategoriesNames($ids)
	{
		$this->db->select('cat.id, cat.pName, cat.tPage as pageId, page.pName as pageName, page.pUrl');
		if (is_array($ids)){
			$this->db->where_in('self.tArticle', $ids);
		} else {
			$this->db->where('self.tArticle', $ids);
		}
		$this->db->join('category cat', 'self.tCategory = cat.id');
		$this->db->join('page', 'page.id = cat.tPage');
		$res = $this->db->get('article_category self')->result();
		$ret = array();
		foreach ($res as $val) {
			$ret[$val->id] = $val;
		}
		return $ret;
	}

	function getArticleCategoriesWithGroup($ids)
	{
		if (!$ids) {
			return array();
		}
		$this->db->where_in('tArticle', $ids);
		$res = $this->db->get('article_category')->result();
		if ($res) {
			$ret = array();
			foreach ($res as $val) {
				$ret[$val->tArticle][] = $val->tCategory;
			}
			return $ret;
		} else {
			return array();
		}
	}
}